package com.heima.app.gateway.filter;


import com.heima.app.gateway.until.AppJwtUtil;

import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
@Slf4j
public class AuthorizeFilter implements GlobalFilter , Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpResponse response = exchange.getResponse();
        ServerHttpRequest request = exchange.getRequest();

        //判断是否登录
        String path = request.getURI().getPath();
        if (path.contains("/login_auth")){
           return chain.filter(exchange);
        }

        //获取token 如果没有则返回401
        String token = request.getHeaders().getFirst("token");
        if (StringUtils.isEmpty(token)) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        //获取token 验证token是否有效
        try {
            Claims claimsBody = AppJwtUtil.getClaimsBody(token);
            int status = AppJwtUtil.verifyToken(claimsBody);

            if (status == 1 || status == 2) {
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return response.setComplete();
            }else{

                //获取用户id
                String userId = claimsBody.get("id").toString();
                //对请求对象request进行增强
                ServerHttpRequest req = request.mutate().headers(httpHeaders ->
                        //httpHeaders封装所有请求头
                        httpHeaders.set("userId", userId)
                ).build();
                exchange.mutate().request(req);


                return chain.filter(exchange);
            }

        } catch (Exception e) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
    }


    @Override
    public int getOrder() {
        return 0;
    }
}
